package lib

import (
	"encoding/json"
	"fmt"
	"github.com/kevin186/casbin/models"
	"log"
	"time"
)

type RoleRel struct {
	PRole string
	Role  string
}

func (this *RoleRel) String() string {
	return this.PRole + ":" + this.Role
}

//获取角色
func GetRoles(pid int, m *[]*RoleRel, pname string) {
	proles := make([]models.Role, 0)
	//var proles []models.Role
	DB.Where("role_pid = ?", pid).First(&proles)
	//DB.Exec("select * from roles where role_pid = 0").Find(&proles)
	fmt.Println("start search sql")
	//DB.Find(&proles)
	if len(proles) == 0 {
		fmt.Println("proles is null")
		return
	}
	for _, item := range proles {
		fmt.Println("proles 循环中role Code：", item.Code)
		if pname != "" {
			fmt.Printf("pname is ：%s , roleName is : %s \n", pname, item.RoleName)
			*m = append(*m, &RoleRel{pname, item.RoleName})
		}
		fmt.Println("start getRoles item.Code :", item.Code)
		time.Sleep(time.Second)
		// TODO 此处死循环，创建role的id与role-pid初始值相同，此处造成死循环
		GetRoles(int(item.Code), m, item.RoleName)
		fmt.Println("end getRoles item.Code :", item.Code)
	}
}

func GetUserRoles() (users []models.User) {

	//DB.Select("a.user_name,c.role_name ").Table("users a,users_roles b ,roles c ").
	//	Where("a.id=b.user_id and b.role_id=c.role_id").
	//	Order("a.user_id desc").Find(&users)

	//users = []*models.User{}
	//fmt.Println("123")
	//DB.Preload("roles").Find(&users)
	//res, err := json.Marshal(users)
	//if err != nil {
	//	panic(err)
	//}
	//fmt.Println(string(res))

	users = []models.User{
		//UserName: "User1",
	}
	err := DB.Preload("Roles").Find(&users).Error
	if err != nil {
		log.Fatal("Failed to query data: ", err)
	}

	res, err := json.Marshal(users)
	if err != nil {
		log.Fatal("Failed to marshal data:", err)
	}
	fmt.Println("获取到的users为：" + string(res))

	return users
}

//获取路由和角色对应关系
func GetRouterRoles() (routers []models.Router) {
	//DB.Select("a.r_uri,a.r_method,c.role_name").
	//	Table("routers a,router_roles b,roles c ").
	//	Where(" a.r_id=b.router_id and b.role_id=c.role_id").
	//	Order(" role_name").Find(&routers)

	routers = []models.Router{
		//UserName: "User1",
	}
	err := DB.Preload("Roles").Find(&routers).Error
	if err != nil {
		log.Fatal("Failed to query data: ", err)
	}

	res, err := json.Marshal(routers)
	if err != nil {
		log.Fatal("Failed to marshal data:", err)
	}
	fmt.Printf("获取到的routers数量为：%d, 内容为：%s\n", len(routers), string(res))
	//for _, v := range routers {
	//	fmt.Printf("获取到的routers中role数量为：%d, 内容为：%v\n", len(v.Roles), v.Roles)
	//}

	return
}
